var throttling = (function () {
  var t = null;
  return function (callback, delay = 200) {
    // 如果t不是null那么我们就不允许代码执行; 
    if (t !== null) {
      return;
    }
    t = setTimeout(function () {
      // 放入你想要执行的代码; 
      callback();
      // 重置t;
      t = null;
    }, delay)
  }
})();


class LazyLoad {
  constructor(selector) {
    this.imgs = Array.from(document.querySelectorAll(selector))
    console.log(this.imgs);
    this.top_list = this.imgs.map(ele => this.getAbsTop(ele));
    //BUG 只要页面不滚动，首屏图片是无法显示的; 
    this.bindEvent();
    window.dispatchEvent(new Event("scroll"));

  }
  getAbsTop(ele) {
    // 你当前的定位元素是不是body; 
    if (ele.offsetParent !== document.body) {
      return ele.offsetTop + this.getAbsTop(ele.offsetParent)
    }
    return ele.offsetTop;
  }
  bindEvent() {
    // 给页面绑定卷动事件; 
    window.addEventListener("scroll", () => {
      // throttling(this.toggleAttr.bind(this));
      console.log(1);
    })
  }

  toggleAttr() {
    for (let i = 0; i < this.top_list.length; i++) {
      if (this.top_list[i] <= scrollY + innerHeight) {
        // 图片如果已经加载了那就直接删除掉这个图片就可以了; 
        let loadImg = new Image();
        console.log(this.imgs[i].getAttribute("data-src"));
        loadImg.src = this.imgs[i].getAttribute("data-src");

        let img = this.imgs[i]

        loadImg.onload = () => {
          img.src = img.getAttribute("data-src");
        }
        this.imgs.splice(i, 1)
        this.top_list.splice(i, 1)
        i--;
        // 删除掉对应的元素和高度信息; 

      }
    }
  }

}